#include "whitenoise.h"
#include <QVBoxLayout>
#include <QMediaContent>
#include <QFileInfo>
// 构造函数：初始化控件和布局
WhiteNoise::WhiteNoise(QWidget *parent)
    : QWidget(parent), mediaPlayer(new QMediaPlayer(this)), isPlaying(false) {

    QVBoxLayout *layout = new QVBoxLayout(this);

    noiseSelector = new QComboBox(this);
    noiseSelector->addItem("温暖火苗", "src/plugins/myClock/noise/flame.wav");
    noiseSelector->addItem("伞下雨声", "src/plugins/myClock/noise/rain.wav");
    noiseSelector->addItem("舒缓海浪", "src/plugins/myClock/noise/sea.wav");
    noiseSelector->addItem("夏夜虫鸣", "src/plugins/myClock/noise/chirping.wav");

    // 创建播放/暂停按钮
    playPauseButton = new QPushButton("播放", this);

    // 布局控件
    layout->addWidget(noiseSelector);
    layout->addWidget(playPauseButton);

    // 连接信号与槽
    connect(playPauseButton, &QPushButton::clicked, this, &WhiteNoise::togglePlayback);
    connect(noiseSelector, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &WhiteNoise::loadNoise);
    connect(mediaPlayer, &QMediaPlayer::mediaStatusChanged, this, &WhiteNoise::onMediaStatusChanged);

    // 加载默认白噪音（第一个选项）
    loadNoise(0);
}

// 析构函数：清理动态分配的资源
WhiteNoise::~WhiteNoise() {
    if (mediaPlayer) {
        mediaPlayer->stop();
    delete mediaPlayer;
    }

}

// 加载选定的白噪音文件
void WhiteNoise::loadNoise(int index) {
    QString noiseFile = noiseSelector->currentData().toString();

    // 创建 QMediaContent 对象
    QMediaContent mediaContent(QUrl::fromLocalFile(QFileInfo(QString(noiseFile)).absoluteFilePath()));
    mediaPlayer->setMedia(mediaContent);
    // 如果正在播放，切换音频后自动播放新文件
    if (isPlaying) {
        mediaPlayer->play();
    }
}

// 切换播放和暂停
void WhiteNoise::togglePlayback() {
    if (!mediaPlayer) return; // 确保媒体播放器可用

    if (isPlaying) {
        // 如果正在播放，暂停
        mediaPlayer->pause();
        isPlaying = false;
        playPauseButton->setText("播放");
    } else {
        // 如果未播放，开始播放
        mediaPlayer->play();
        isPlaying = true;
        playPauseButton->setText("暂停");
    }
}

// 处理媒体状态变化（用于实现单曲循环）
void WhiteNoise::onMediaStatusChanged(QMediaPlayer::MediaStatus status) {
    if (status == QMediaPlayer::EndOfMedia) {
        // 播放结束后重新播放，跳到音频的开始
        mediaPlayer->setPosition(0); // 重置播放位置到开头
        mediaPlayer->play();          // 继续播放
    }
}